import config from "./config";
import * as TextEncoding from "./TextEncoding";
const { sendKey , mKey } = config;
export default class Search {
  UDP;
  pageContext;
  messageQueue = []; // 消息队列
  #_roomList = [];
  goBackGameIp = undefined;
  frequency = 0; // 查询次数

  constructor(parameters) {
    this.pageContext = parameters;
    this.create();
  }

  // 初始化 创建房间
  create() {
    this.UDP = wx.createUDPSocket();
    this.UDP.bind(config.searchPort);
    this.onMessage();
  }
  get roomList() {
    return this.#_roomList;
  }

  set roomList(value) {
    this.#_roomList = value;
    if (this.pageContext && this.pageContext.setData) {
      this.pageContext.setData({ roomList: value });
    }
  }

  // 发送消息
  send(message = {}, address = config.broadcast, port = config.servePort) {
    this.UDP && this.UDP.send({
        address,
        message: JSON.stringify(message),
        port,
    });
  }

  // 接收消息
  onMessage() {
    this.UDP.onMessage((e) => {
      const decoder = new TextEncoding.TextDecoder("utf-8");
      const message = JSON.parse(decoder.decode(new Uint8Array(e.message)));
      const gameIp = e.remoteInfo.address;
      // 处理需要回复的消息（立即回复）前提是客户端还在
      if (message[mKey.isNeedReply] === 1) {
        this.send({[mKey.backMessageTryId]: message[mKey.messageId]},
          gameIp
        );
      }

      wx.hideLoading();

      // 处理重复消息
      if (this._isDuplicateMessage(message)) {
        return;
      }

      // 服务端发来房间数据 ---- 发送服务端确认
      if (message[mKey.messageType] === sendKey.client_get_game) {
        this.frequency = 0
        const roomList = this.roomList;
        const roomIndex = roomList.findIndex(
          (d) => d.roomId === message[mKey.roomId]
        );
        const gameMessage = {
          gameIp,
          roomId: message[mKey.roomId],
          count:message[mKey.count],
          userCount:message[mKey.userCount],
        }
        if (roomIndex !== -1) {
          roomList[roomIndex] = gameMessage;
        } else {
          roomList.push(gameMessage);
        }
        this.roomList = roomList;

        // 判断用户是否是  返回
        if (message[mKey.presence]) {
          this.pageContext.setData({ modalCole: 16 });
          this.goBackGameIp = gameIp;
        }
        return;
      }

      // 服务端解散房间
      if (message[mKey.messageType] === sendKey.close_game) {
        const roomList = this.roomList;
        const roomIndex = roomList.findIndex(
          (d) => d.gameIp === gameIp
        );
        if (roomIndex !== -1) {
          roomList.splice(roomIndex, 1);
        }
        this.roomList = roomList;
        return;
      }
    });
  }

  // 检查是否是重复消息
  _isDuplicateMessage(message) {
    if (!message[mKey.messageId]) {
      return false;
    }
    const key = `${message[mKey.messageId]}`;
    if (this.messageQueue.includes(key)) {
      return true;
    }
    this.messageQueue.push(key);
    // 保持队列在合理大小
    if (this.messageQueue.length > 1000) {
      this.messageQueue.shift();
    }
    return false;
  }

  // 不返回房间 退出
  goBackNot() {
    this.send({ [mKey.messageType]: sendKey.client_exit_room},this.goBackGameIp);
    this.goBackGameIp = undefined;
    this.pageContext.setData({ modalCole: 0 });
  }
  // 确认返回房间
  goBackOk() {
    wx.navigateTo({
      url: `/pages/cRoom/cRoom?ip=${this.goBackGameIp}&back=1`,
    });
    this.pageContext.setData({ modalCole: 0 });
  }

  // 销毁
  destroy() {
    this.frequency = 0
    this.UDP.close();
    this.UDP.offMessage();
    this.UDP = null;
    this.roomList = [];
    this.messageQueue = []; // 消息队列
  }

  // 初始化搜索游戏
  createGetGame() {
    this.send({ [mKey.messageType]: sendKey.client_get_game });
  }
  // 客户端搜索游戏
  SearchGetGame() {
    const _this = this;
    this.destroy();
    this.create();
    wx.showLoading({
      title: "搜索中...",
      mask: true,
    });
    setTimeout(function () {
      wx.hideLoading();
      if(_this.frequency < 2){
        _this.frequency++
      }else{
        _this.frequency = 0
        _this.pageContext.setData({ modalCole: 34 });
      }
    }, 2000);
    const message = {
      [mKey.messageType]: sendKey.client_get_game,
    };
    this.send(message);
  }
}
